package com.lw.leetcode.hash.b;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 648. 单词替换
 * 剑指 Offer II 063. 替换单词
 *
 * @Author liw
 * @Date 2021/6/15 22:17
 * @Version 1.0
 */
public class ReplaceWords {
    public String replaceWords(List<String> roots, String sentence) {
        Map<String, Integer> map = new HashMap<>();
        for (String root : roots) {
            map.put(root, 1);
        }
        StringBuilder ans = new StringBuilder(sentence.length());
        for (String word : sentence.split("\\s+")) {
            String prefix = "";
            int length = word.length();
            for (int i = 1; i <= length; ++i) {
                prefix = word.substring(0, i);
                if (map.get(prefix) != null) {
                    break;
                }
            }
            ans.append(" ");
            ans.append(prefix);
        }
        return ans.substring(1);
    }

}
